//
//  Tools.m
//  AiMeiTu
//
//  Created by apple on 2018/6/6.
//  Copyright © 2018年 zpf. All rights reserved.
//

#import "Tools.h"
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonDigest.h>
#import <netdb.h>
#import <arpa/inet.h>
#import "AppDelegate.h"

static NSString *const AES_128_KEY = @"";
static NSString *const AES_128_IV  = @"";

@implementation Tools

//通过文字来计算文字所占的区域大小
+ (CGSize)sizeForText:(NSString *)text withFont:(UIFont *)font withSize:(CGSize)size
{
    if (!font) {
        //如果没有的字体 这里用系统15号代替 配合font_WithName:一起使用
        font = [UIFont systemFontOfSize:15];
    }
    NSDictionary *attributes = @{NSFontAttributeName:font};
    
    //通过文字来获取文字所占的大小
    CGRect rect = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
    return rect.size;
}

//设置行高
+(NSAttributedString *)getAttributedStringWithString:(NSString *)string lineSpace:(CGFloat)lineSpace{
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = lineSpace; // 调整行间距
    NSRange range = NSMakeRange(0, [string length]);
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
    return attributedString;
}

//设置控件部分圆角 UIRectCornerTopLeft|UIRectCornerTopRight|UIRectCornerBottomLeft|UIRectCornerBottomRight
+ (void)setRoundAngleView:(UIView *)aView cornerRadius:(CGFloat)radius byRoundingCorners:(UIRectCorner)corners {
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:aView.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = aView.bounds;
    maskLayer.path = maskPath.CGPath;
    aView.layer.mask = maskLayer;
}



//通过文件名获取文件路径
+ (NSString *)filePathWithFileName:(NSString *)fileName{
    //获取数据所在的文件路径
    NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
    return filePath;
}

//十六进制颜色
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    
    //r
    NSString *rString = [cString substringWithRange:range];
    
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}


//获取当前时间的时间戳
+(double)getCurrentTimeStamp{
    NSDate *dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970];
    return a;
}
//时间转date
+(NSDate *)getDate:(NSString *)datestr{
    NSDateFormatter * formatter = [[NSDateFormatter alloc]init];
    // 注意的是下面给格式的时候,里面一定要和字符串里面的统一
    // 比如:   dateStr为2017-07-24 17:38:27   那么必须设置成yyyy-MM-dd HH:mm:ss, 如果你设置成yyyy--MM--dd HH:mm:ss, 那么date就是null, 这是需要注意的
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSDate * date = [formatter dateFromString:datestr];
    return date;
}

//时间戳转换成时间
+(NSString *)dateWithTime:(NSString *)timeStr type:(NSString *)type{
    
    NSTimeInterval time = [timeStr doubleValue]/1000;
    NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    // 实例化一个NSDateFormatter对象，设定时间格式，这里可以设置成自己需要的格式
    if (type.length == 0) {
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    }else{
        [dateFormatter setDateFormat:type];
    }
    
    NSString *dateStr = [dateFormatter stringFromDate:detailDate];
    
    return dateStr;
}

//不同格式时间转换 默认原来的是yyyyMMddHHmmss
+(NSString *)dateWithTime:(NSString *)timeStr OriginalFormatter:(NSString *)oriFormatterStr expectFormatter:(NSString *)expFormatterStr {
    
    if (oriFormatterStr == nil || oriFormatterStr.length == 0) {
        oriFormatterStr = @"yyyyMMddHHmmss";
    }
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:oriFormatterStr];
    NSDate *aDate = [dateFormatter dateFromString:timeStr];
    
    //自定义星期显示
    dateFormatter.weekdaySymbols = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六"];
    [dateFormatter setDateFormat:expFormatterStr];
    NSString *dateString = [dateFormatter stringFromDate:aDate];
    
    return dateString;
}


//四舍五入
+(NSInteger)RoundingOff:(CGFloat)floatValue{
    NSInteger intNumber = floatValue/1;
    CGFloat floatNumber = floatValue-intNumber;
    if (floatNumber>=0.5) {
        intNumber = intNumber + 1;
    }
    return intNumber;
}

//md5加密
+(NSString *)MD5WithString:(NSString *)str{
    NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];//加密后的长度
    /**
     CC_MD5(const void *data, CC_LONG len, unsigned char *md)
     
     data：是将要加密的数据
     len：代表需要加载的数据长度
     md：是加密之后的密文
     */
    CC_MD5(stringData.bytes, (CC_LONG)stringData.length, result);
    NSMutableString *resultStr = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i ++) {
        [resultStr appendFormat:@"%02x",result[i]];
    }
    return resultStr;
}

//sha1加密
+ (NSString *)sha1WithString:(NSString *)input {
    
    //加密无中文字符串
//    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
//    NSData *data = [NSData dataWithBytes:cstr length:input.length];
//
//    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
//    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
//    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
//
//    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
//        [output appendFormat:@"%02x", digest[i]];
//    }
//    return output;
    
    
    
    //可加密带有中文字符的
    
    //这两句容易造成 、中文字符串转data时会造成数据丢失
    //const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    //NSData *data = [NSData dataWithBytes:cstr length:input.length];
    //instead of
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

//MD5+sha1 MD5外层
+ (NSString *)sha1_md5WithString:(NSString *)input {
    NSString *sha1Str = [self sha1WithString:input];
    return [self MD5WithString:sha1Str];
}





//根据图片二进制流获取图片格式
+ (NSString *)typeForImageData:(NSData *)data {
    
    uint8_t c;
    [data getBytes:&c length:1];
    
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
    }
    return @"jpg";
}

//获取缓存大小
+ (CGFloat)getCacheSize {
    //这里主要清理图片缓存数据以及临时文件 因为NSDocumentDirectory文件未存用户数据 故不清理
    CGFloat size = [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject] + [self folderSizeAtPath:NSTemporaryDirectory()];
    return size;
}

//根据路径计算目录大小
+ (CGFloat)folderSizeAtPath:(NSString *)path{
    // 利用NSFileManager实现对文件的管理
    NSFileManager *manager = [NSFileManager defaultManager];
    CGFloat size = 0;
    if ([manager fileExistsAtPath:path]) {
        // 获取该目录下的文件，计算其大小
        NSArray *childrenFile = [manager subpathsAtPath:path];
        for (NSString *fileName in childrenFile) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize;
        }
        // 将大小转化为M
        return size/1024.0/1024.0;
    }
    return 0;
}

//清除缓存
+ (void)clearAllCacheSucc:(ToolsBlock)succBlock {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 利用NSFileManager实现对文件的管理
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //删除NSCachesDirectory
        NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
        if ([fileManager fileExistsAtPath:path]) {
            // 获取该路径下面的文件名
            NSArray *childrenFiles = [fileManager subpathsAtPath:path];
            for (NSString *fileName in childrenFiles) {
                // 拼接路径
                NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
                // 将文件删除
                [fileManager removeItemAtPath:absolutePath error:nil];
            }
        }
        //删除Tmp
        path = NSTemporaryDirectory();
        if ([fileManager fileExistsAtPath:path]) {
            // 获取该路径下面的文件名
            NSArray *childrenFiles = [fileManager subpathsAtPath:path];
            for (NSString *fileName in childrenFiles) {
                // 拼接路径
                NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
                // 将文件删除
                [fileManager removeItemAtPath:absolutePath error:nil];
            }
        }
        
        //返回主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            if (succBlock) {
                succBlock(@"");
            }
        });
    });
}



+ (void)endRefreshWithTable:(UITableView *)tableView {
    dispatch_async(dispatch_get_main_queue(), ^{
      
    });
}

+ (void)endRefreshWithCollect:(UICollectionView *)collect {
    
}

/*mov格式视频转换为MP4格式  movUrl mov视频路径 @result  MP4格式视频路径 */
 

//s转hh:mm:ss
+(NSString *) getHmsWithDisTime:(NSInteger)disTime {
    NSString *hour = [NSString stringWithFormat:@"%.2ld",disTime/60/60];
    NSString *min = [NSString stringWithFormat:@"%.2ld",disTime/60%60];
    NSString *sec = [NSString stringWithFormat:@"%.2ld",disTime%60%60];
    return [NSString stringWithFormat:@"%@:%@:%@",hour,min,sec];
}
+ (CGImageRef)drawImage:(CGImageRef)cgimage
{
    size_t width = CGImageGetWidth(cgimage); // 图片宽度
    size_t height = CGImageGetHeight(cgimage); // 图片高度
    unsigned char *data  = calloc(width * height * 4, sizeof(unsigned char)); // 取图片首地址
    size_t bitsPerComponent = 8; // r g b a 每个component bits数目
    size_t bytesPerRow = width * 4; // 一张图片每行字节数目 (每个像素点包含r g b a 四个字节)
    CGColorSpaceRef space = CGColorSpaceCreateDeviceRGB(); // 创建rgb颜色空间
    
    CGContextRef context =
    CGBitmapContextCreate(data,
                          width,
                          height,
                          bitsPerComponent,
                          bytesPerRow,
                          space,
                          kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), cgimage);
    
    for (size_t i = 10; i < height; i++)
    {
        for (size_t j = 10; j < width; j++)
        {
            size_t pixelIndex = i * width * 4 + j * 4;
            
            unsigned char red = data[pixelIndex];
            unsigned char green = data[pixelIndex + 1];
            unsigned char blue = data[pixelIndex + 2];
            
            //过滤代码
            if (red == 0 && green == 0 && blue == 0) {
                //设置成白色
                data[pixelIndex] = 255;
                data[pixelIndex + 1] = 255;
                data[pixelIndex + 2] = 255;
            }else {
            
                data[pixelIndex] = 0;
                data[pixelIndex + 1] = 0;
                data[pixelIndex + 2] = 0;
            }
                
        }
    }
    
    cgimage = CGBitmapContextCreateImage(context);
    return cgimage;
}

#pragma mark - app private
// 根据图片url获取图片尺寸
+(CGSize)getImageSizeWithURL:(id)imageURL
{
    NSURL* URL = nil;
    if([imageURL isKindOfClass:[NSURL class]]){
        URL = imageURL;
    }
    if([imageURL isKindOfClass:[NSString class]]){
        URL = [NSURL URLWithString:imageURL];
    }
    if(URL == nil)
        return CGSizeZero;                  // url不正确返回CGSizeZero
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:URL];
    NSString* pathExtendsion = [URL.pathExtension lowercaseString];
    
    CGSize size = CGSizeZero;
    if([pathExtendsion isEqualToString:@"png"]){
        size =  [self getPNGImageSizeWithRequest:request];
    }
    else if([pathExtendsion isEqual:@"gif"])
    {
        size =  [self getGIFImageSizeWithRequest:request];
    }
    else{
        size = [self getJPGImageSizeWithRequest:request];
    }
    if(CGSizeEqualToSize(CGSizeZero, size))                    // 如果获取文件头信息失败,发送异步请求请求原图
    {
        NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:URL] returningResponse:nil error:nil];
        UIImage* image = [UIImage imageWithData:data];
        if(image)
        {
            size = image.size;
        }
    }
    return size;
}
//  获取PNG图片的大小
+(CGSize)getPNGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=16-23" forHTTPHeaderField:@"Range"];
    
//    //1.创建NSURLSession对象（可以获取单例对象）
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURLSessionDataTask * dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        //data
//
//        //注意：刚创建出来的task默认是挂起状态的，需要调用该方法来启动任务（执行任务）
//        [dataTask resume];
//    }];
    
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 8)
    {
        int w1 = 0, w2 = 0, w3 = 0, w4 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        [data getBytes:&w3 range:NSMakeRange(2, 1)];
        [data getBytes:&w4 range:NSMakeRange(3, 1)];
        int w = (w1 << 24) + (w2 << 16) + (w3 << 8) + w4;
        int h1 = 0, h2 = 0, h3 = 0, h4 = 0;
        [data getBytes:&h1 range:NSMakeRange(4, 1)];
        [data getBytes:&h2 range:NSMakeRange(5, 1)];
        [data getBytes:&h3 range:NSMakeRange(6, 1)];
        [data getBytes:&h4 range:NSMakeRange(7, 1)];
        int h = (h1 << 24) + (h2 << 16) + (h3 << 8) + h4;
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取gif图片的大小
+(CGSize)getGIFImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=6-9" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data.length == 4)
    {
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0, 1)];
        [data getBytes:&w2 range:NSMakeRange(1, 1)];
        short w = w1 + (w2 << 8);
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(2, 1)];
        [data getBytes:&h2 range:NSMakeRange(3, 1)];
        short h = h1 + (h2 << 8);
        return CGSizeMake(w, h);
    }
    return CGSizeZero;
}
//  获取jpg图片的大小
+(CGSize)getJPGImageSizeWithRequest:(NSMutableURLRequest*)request
{
    [request setValue:@"bytes=0-209" forHTTPHeaderField:@"Range"];
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    if ([data length] <= 0x58) {
        return CGSizeZero;
    }
    
    if ([data length] < 210) {// 肯定只有一个DQT字段
        short w1 = 0, w2 = 0;
        [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
        [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
        short w = (w1 << 8) + w2;
        short h1 = 0, h2 = 0;
        [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
        [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
        short h = (h1 << 8) + h2;
        return CGSizeMake(w, h);
    } else {
        short word = 0x0;
        [data getBytes:&word range:NSMakeRange(0x15, 0x1)];
        if (word == 0xdb) {
            [data getBytes:&word range:NSMakeRange(0x5a, 0x1)];
            if (word == 0xdb) {// 两个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0xa5, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0xa6, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0xa3, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0xa4, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            } else {// 一个DQT字段
                short w1 = 0, w2 = 0;
                [data getBytes:&w1 range:NSMakeRange(0x60, 0x1)];
                [data getBytes:&w2 range:NSMakeRange(0x61, 0x1)];
                short w = (w1 << 8) + w2;
                short h1 = 0, h2 = 0;
                [data getBytes:&h1 range:NSMakeRange(0x5e, 0x1)];
                [data getBytes:&h2 range:NSMakeRange(0x5f, 0x1)];
                short h = (h1 << 8) + h2;
                return CGSizeMake(w, h);
            }
        } else {
            return CGSizeZero;
        }
    }
}
//判断是否登录
//判断手机格式
+ (BOOL)isValidPhone:(NSString *)phone{
    if (phone.length != 11) {
        return NO;
    }
    if (![[phone substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"1"]) {
        return NO;
    }
    return YES;
}
+ (CGFloat)safeAreaInsetsbottom{
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    if (@available(iOS 11.0, *)) {
        return window.safeAreaInsets.bottom;
    } else {
        return 34.0;
    }
}

+ (CGFloat)safeAreaInsetstop{
    UIWindow *window = UIApplication.sharedApplication.keyWindow;
    if (@available(iOS 11.0, *)) {
        return window.safeAreaInsets.top;
    } else {
        return 24.0;
    }
}
+(NSDictionary *)dealWithNullData:(NSDictionary *)dic{
//    NSLog(@"转化的==%@",dic);
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:dic];
    for (NSString *key in dict.allKeys) {
        if ( [dict[key] isKindOfClass:[NSDictionary class]]) {
            [dict setObject:[self dealWithNullData:dict[key]] forKey:key];
        }else if ( [dict[key] isKindOfClass:[NSArray class]]) {
            [dict setObject:[self dealWithNullDataArr:dict[key]] forKey:key];
        }else{
            if ([dict[key] isEqual:[NSNull null]]) {
                [dict removeObjectForKey:key];
            }
        }
    }
    return dict;
}
+(NSArray *)dealWithNullDataArr:(NSArray *)arr{
    NSMutableArray * addarr = [NSMutableArray new];
    for (int i=0; i<arr.count; i++) {
        if ([arr[i] isKindOfClass:[NSDictionary class]]) {
            [addarr addObject:[Tools dealWithNullData:arr[i]]];
        }else if ([arr[i] isKindOfClass:[NSArray class]]) {
            [addarr addObject:[self dealWithNullDataArr:arr[i]]];
        }
        else{
            [addarr addObject:arr[i]];
        }
    }
    return addarr;
}
+ (NSString *)NumberToShowString:(long)number{
    if (number >= 100000000) {
        return [NSString stringWithFormat:@"%.1f亿",number*1.0/100000000.0];
    }else if (number >= 10000) {
        return [NSString stringWithFormat:@"%.1f万",number*1.0/10000.0];
    }else{
        return [NSString stringWithFormat:@"%ld",number];
    }
}

+ (NSString *)imageNameMoshi:(NSString *)name{
    return name;
}
+(NSString *)inputTimeStr:(NSString *)timeStr
{
    timeStr = [Tools dateWithTime:timeStr type:@"yyyy-MM-dd HH:mm:ss"];
    NSDate * olddate = [Tools getDate:timeStr];
    NSTimeInterval timeInterval = [olddate timeIntervalSinceNow];
    timeInterval = -timeInterval+8*3600;
    long temp = 0;
    NSString *result;
    if ([self isYesterdayWithDate:olddate]){//24小时内可能是昨天
        result = [NSString stringWithFormat:@"昨天"];
    }else if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    else if((temp = temp/24) <7){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    else {
        result = timeStr;
    }
    return result;
}
+(UIImage *)getImageSizeToMin:(UIImage *)img{

    UIGraphicsBeginImageContext(CGSizeMake(200, 200));
        [img drawInRect:CGRectMake(0,0,200,200)];
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    return [UIImage imageWithData:UIImageJPEGRepresentation(newImage, 0.8)];
}
//把时间转换成星期

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate {



 NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];



 NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];



 //    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

 NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"zh-Hans"];



[calendar setTimeZone: timeZone];



 NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;



 NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];



 return [weekdays objectAtIndex:theComponents.weekday];

}
//判断是否为昨天
+ (BOOL)isYesterdayWithDate:(NSDate *)newDate
{
    BOOL isYesterday = YES;
    NSTimeInterval secondsPerDay= 24 * 60 * 60;
    NSDate *yearsterDay = [[NSDate alloc] initWithTimeIntervalSinceNow:-secondsPerDay];
    NSCalendar* calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents* comp1 = [calendar components:unitFlags fromDate:newDate];
    NSDateComponents* comp2 = [calendar components:unitFlags fromDate:yearsterDay];
    if ( comp1.year == comp2.year && comp1.month == comp2.month && comp1.day == comp2.day)
    {
        isYesterday = YES;
    }else {
        isYesterday = NO;
    }
    return isYesterday;
}
+ (NSURL *)urlToNsurl:(NSString *)str{
    NSString *headImgURL = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];

    return [NSURL URLWithString:headImgURL];
}
@end
